import time
from selenium import webdriver


class login_util():
    driver = None

    # 变量前面加self,表示当前变量为全局变量
    # 构造函数,当生命这个对象的时候,会自动执行这个函数
    def __init__(self, browser_type):
        if browser_type == 'chrome':
            self.driver = webdriver.Chrome()
        elif browser_type == 'firefox':
            self.driver = webdriver.Firefox()
        else:
            self.driver = None
        self.driver.maximize_window()

    def request(self, url):
        self.driver.get(url)
        # 设置隐式等待---每隔0.5s就会去查找元素,直到查找到页面元素或者超出规定时间
        # 如果同时设置了隐式等待和显示等待，并且隐式等待的时间大于显示等待，那么以隐式等待为主
        self.driver.implicitly_wait(3)

    def getElement(self, method_type, data):
        element = None
        if method_type == "id":
            element = self.driver.find_element_by_id(data)
        elif method_type == "class":
            element = self.driver.find_element_by_class_name(data)
        elif method_type == "name":
            element = self.driver.find_element_by_name(data)
        elif method_type == "tag":
            element = self.driver.find_element_by_tag_name(data)
        elif method_type == "xpath":
            element = self.driver.find_element_by_xpath(data)
        elif method_type == "text":
            element = self.driver.find_element_by_link_text(data)
        elif method_type == "link":
            element = self.driver.find_element_by_partial_link_text(data)
        elif method_type == "css":
            element = self.driver.find_elements_by_css_selector(data)
        return element

    # 清除
    def upclear(self, method_type, data):
        element = self.getElement(method_type, data)
        element.clear()

    # 输入值
    def send_keys(self, method_type, data, value):
        element = self.getElement(method_type, data)
        element.send_keys(value)

    # 点击
    def click(self, method_type, data):
        element = self.getElement(method_type, data)
        element.click()

    # 退出
    def qt(self):
        time.sleep(3)
        self.driver.quit()